package virtual.utils;

import android.app.Application;
import android.content.Context;
import android.util.Log;


import java.util.ArrayList;
import java.util.List;

import virtual.Virtuals;
import virtual.disk.AppUtils;
import virtual.models.AppData;
import virtual.models.AppInfo;
import virtual.models.AppInfoLite;
import virtual.models.MultiplePackageAppData;
import virtual.repo.AppDataSource;
import virtual.repo.AppRepository;

public class VirtualAppHepler {
    private Context mContext;
    private AppDataSource mRepository;
    private AppVirtualUtils appVirtualUtils;

    public VirtualAppHepler(Context mContext) {
        this.mContext = mContext;
        mRepository = new AppRepository(mContext);
        appVirtualUtils = new AppVirtualUtils(mContext);
    }


    /***
     * 安装所有可用游戏APP
     */
    public void initInstallAllApk(String... apkName) {
        String dataDiskList = Virtuals.getDiskLruCacheHelper().getAsString("AppInfoLite");
        if (dataDiskList != null){
            return;
        }

        assetsToFiles(mContext,apkName);
        mRepository.getStorageApps(mContext, mContext.getCacheDir()).done(this::loadFinish);
    }

    public void assetsToFiles(Context context,String... fileName){
        for (String name: fileName) {
            AppUtils.copyAssetsFile(context,name,context.getCacheDir().getPath());
        }
    }

    /***
     * APK加载完成
     * @param infoList
     */
    public void loadFinish(List<AppInfo> infoList) {
        ArrayList<AppInfoLite> dataList = new ArrayList<AppInfoLite>(infoList.size());
        for (AppInfo info : infoList) {
            dataList.add(new AppInfoLite(info.packageName, info.path, info.fastOpen));
        }

        Virtuals.getDiskLruCacheHelper().put("AppInfoLite",dataList);
        for (AppInfoLite info : dataList) {
            appVirtualUtils.addApp(info);
        }
        appVirtualUtils.setOnAppStatusListener(new AppVirtualUtils.OnAppStatusListener() {
            @Override
            public void setInstallData(AppData installAppData) {
                Log.d("loadFinish: ","***1"+installAppData);
                if (installAppData instanceof MultiplePackageAppData){
                    Virtuals.getDiskLruCacheHelper().put("MultiplePackageAppData",(MultiplePackageAppData)installAppData);
                }
            }

            @Override
            public void setRefreshData(AppData refreshData) {
                Log.d("setRefreshData: ","***2"+refreshData);
            }

            @Override
            public void setRemoveAppRefreshData(AppData removeAppData) {
                Log.d("setRemoveAppRefreshData","***3"+removeAppData);
            }
        });
    }
}
